package com.ctg.behavior.calc.impala.builder.ltv;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtCalcDate;
import com.ctg.behavior.calc.impala.report.ltv.CtLTVMeasureReport;
import com.ctg.behavior.calc.utils.CtCalcDaysUtils;
import com.ctg.behavior.common.ltv.CtLTVCalcBody;
import com.ctg.behavior.common.ltv.CtLTVMeasure;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtLTVMeasureReportBuilder {

	/****************************************************************
	 * 
	 */
	public List<CtLTVMeasureReport> doBuilder(CtLTVCalcBody calcBody) {

		log.info("calcBody={}", JSON.toJSONString(calcBody));

		List<CtLTVMeasureReport> calcReports = new ArrayList<>();

		for (CtLTVMeasure ltvMeasure : calcBody.getMeasures()) {
			String fromDate = calcBody.getFromDate();
			String toDate = calcBody.getToDate();
			log.info("fromDate={},toDate={}", fromDate, toDate);
			List<String> calcDays = CtCalcDaysUtils.listCalcDayList(fromDate, toDate);
			for (String calcDay : calcDays) {
				List<CtCalcDate> ltvCalcDate = CtCalcDaysUtils.listLTVCalcDays(calcDay, toDate);
				if (ltvCalcDate.isEmpty()) {
					log.info("ltvCalcDate is Empty, calcDay={},toDate={}", calcDay, toDate);
					continue;
				}
				CtLTVMeasureReport measureReport = this.copyBody(calcBody);
				measureReport.setMeasure(ltvMeasure);
				measureReport.setCellDates(ltvCalcDate);
				measureReport.setWhichDay(calcDay);
				// 是否计算事件的总次数
				if (!"LTV_AVG".equalsIgnoreCase(ltvMeasure.getAggregator())) {
					measureReport.setIsEventTimes(true);
				}
				calcReports.add(measureReport);
			}
			log.info("calcDays={}", JSON.toJSONString(calcDays));
		}

		log.info("calcReports={}", JSON.toJSONString(calcReports));

		return calcReports;

	}

	public CtLTVMeasureReport copyBody(CtLTVCalcBody body) {
		CtLTVMeasureReport oneReport = new CtLTVMeasureReport();

		oneReport.setAppId(body.getAppId());
		oneReport.setBookmarkId(body.getBookmarkId());
		oneReport.setRequestId(body.getRequestId());

		oneReport.setFromDate(body.getFromDate());
		oneReport.setToDate(body.getToDate());
		oneReport.setUnit(body.getUnit());

		oneReport.setFilter(body.getFilter());

		oneReport.setSubjectId(body.getSubjectId());
		oneReport.setSubTaskType(body.getSubTaskType());
		oneReport.setFilter(body.getFilter());

		oneReport.setByFields(body.getByFields());
		oneReport.setStartSign(body.getStartSign());

		return oneReport;
	}

}
